<template>
	<div>
		<view class="main" v-if="isShow">
			<view class="title">
				<u-image class="title-text" src="@/static/login/login2.png" width="520upx" height="234upx"
					mode="aspectFit"></u-image>
			</view>
			<div class="btn-box">
			<!-- 本地调试、开发-手机号登录 -->
			<!-- <button type="button"  @click="getUserLogin2('15927336006')" style="border:0; padding:12px 20px; background:#2979ff; display:block; width:100%; color:#fff; display:block; margin:20px 0; border-radius:5px;">手机号登录</button> -->
					
			<view v-if="isShow" style="text-align: center; padding:12px 20px; background:#2979ff; display:block; width:100%; color:#fff; display:block; margin:20px 0; border-radius:5px;">
				无访问权限
			</view>
			</div>
		</view>
	</div>
</template> 
<script> 
import $ from 'common/utils/jquery-3.5.1.min.js'
import { baseUrl } from '@/common/request/config';
import { encryptDes, decryptDes  } from '@/common/utils/des.js'
import { watermark, watermarkSet } from '@/common/utils/waterMark2.js'    
	export default {
		data() { 
			return {
				aseKey: '42112119871013604542098319830220',
				phoneNumberServer: null,
				phoneNumber:'',
				disabled:false,
				code: '',
				customStyle: {
					background: '#0071DB',
					width: '530upx',
					height: '102upx',
					fontSize: '38upx',
				},
				OneKeyRepairConfig : {
				    IdentityServer: false,//�Ƿ�������Ȩ������
				    ApiUrl: "https://172.20.10.8:7001/api/",//"http://192.168.137.112:7001/api/",
				    ApiVerson: { v1: "v1.0", v2: "v2.0" },
				    PageSize: 20,
				    PageSizeList: [10, 20, 30, 50, 80, 100],//��ҳ������
				    CharIntervalTimeOut: 10 * 1000
				},
				flagPolicy: false, //是否浏览过隐私政策
				result: null, //测试接口返回的
				border: 0,
				// checkedStatus: false, //同意隐私政策
				list: [{
					name: '同意隐私政策',
					checked: false,
					disabled: false,
				}, ],
				isShow: false,
				datas: ''
				
			};
		},
		onLoad(v) {
				// 	this.phoneNumberServer = new window.PhoneNumberServer();
				// if (this.$route.query.flag == '1') {
				// 	this.flagPolicy = true;
				// 	this.list[0].checked=true
				// } else {
				// 	this.flagPolicy = false;
				// }
				//从浏览器获取token
				this.getUserLogin()
		},
		mounted() {
			if(this.$route.query.Phone){
				this.phoneNumber=decryptDes(this.$route.query.Phone,'desenc1!')
			}
		},
		activated() {
			this.disabled = false;
		},
		methods: {
			async getUserLogin(){
				let token = this.getQueryParam('token') || ''
				let params=`?token=${token}`
				let data = await  this.$api.getphonen(params); //已经封装好的api
				if (data.Code == 200) {
					this.getUserLogin2(data.Data)
				}else {
					this.isShow = true
				}
			},
			async getUserLogin2(Phone){
				let that = this
				uni.removeStorageSync('token'); //清除本地token
				uni.removeStorageSync('userName'); 
				uni.removeStorageSync('phoneNumber'); 
				uni.removeStorageSync('cityName'); 
				let pathValue = that.getQueryParam('pageType') || ''
				//手机号加密
				let PhoneNum = encryptDes(Phone,'desenc1!').replace('+', '%2B')
				let params=`?Phone=${PhoneNum}&type=2&classes=${pathValue == 2 ? '2' : pathValue == 3 ? '3' : pathValue == 4 ? '4' : '1'}`
				let data = await  this.$api.gettokenbyphone(params); //已经封装好的api
			
				if (data.Code == 200) {
					uni.setStorageSync('token', data.Data.access_token); //保存本地token
					uni.setStorageSync('userName',data.Data.realname);
					uni.setStorageSync('phoneNumber', data.Data.phone);
					uni.setStorageSync('cityName', data.Data.cityname);
					//登录成功水印
					let userName = data.Data.realname
					let phoneNumber = data.Data.phone
					let time = that.$timeFormat(new Date(), 'yyyy.mm.dd')
					let text = [userName + phoneNumber, time] 
					if (text) {
						watermark.set(text)
						watermarkSet.setCreateFlag(true)
						watermarkSet.text = text
					}
					
					that.saveToken(data.Data.access_token).then(() => {
						if(pathValue == 1){
							that.$router.push({  //普通日报
							   path:'/pagesJK/overviewPage/index'
							});
						}else if(pathValue == 2){
							that.$router.push({   //2025开门红
							   path:'/pagesJK/agoodStart/index'
							});
							// window.location.href = 'https://webapi.aiflow.com:10002/KMHH5/index.html#/pagesJK/agoodStart/index';
							
						}else if(pathValue == 3){
							// that.$router.push({  //2025春节引导页 - 年报
							//    path:'/pagesJK/yindao/index'
							// });
							window.location.href = 'https://webapi.aiflow.com:10002/KMHH5/index.html#/pagesJK/yindao/index';
						}else if(pathValue == 4){
							// that.$router.push({  //2025春节日报
							//    path:'/pagesJK/dailyNewspaper/index'
							// });
							window.location.href = 'https://webapi.aiflow.com:10002/JKH5/index.html#/pagesJK/dailyNewspaper/index';
						}
						else{
							that.$router.push({  //普通日报
							   path:'/pagesJK/overviewPage/index'
							});
						}
					}).catch(error => {
						console.error('Token存储失败', error);
						// 处理错误，比如提示用户或者进行错误处理
					});
				} else {
					that.isShow = true
				}
			},
			saveToken(token) {
			    return new Promise((resolve, reject) => {
			        // 异步存储token的操作，例如使用uniapp API
			        uni.setStorage({
			            key: 'token',
			            data: token,
			            success: resolve,
			            fail: reject
			        });
			    });
			},
			getQueryParam(paramName) {
			  const url = window.location.hash.slice(1)
			  const params = new URLSearchParams(url.split('?')[1])
			  if (params != null) return params.get(paramName)
			  return null
			},
			checkboxChange(e) {
				this.list[0].checked = e.value;
			},
			toPolicy() {
				this.$router.push({
					type: 'redirectTo',
					path: '/pages/H5Login/privacyPolicy',
					query: {
						type: 'login',
						Phone:encryptDes(this.phoneNumber,'desenc1!')
					},
				});
			},
			async getPhoneLogin(){
				let isPolicy = uni.getStorageSync('policy');
				uni.removeStorageSync('token'); //清除本地token
				try{
					let PhoneNum=encryptDes(this.phoneNumber,'desenc1!').replace('+', '%2B')
					let params=`?Phone=${PhoneNum}`
				    this.gettokenbyphone(params)
				}catch(err){
					uni.showToast({
						title: err.stack,
						icon: 'none',
						duration: 5000,
						mask: true,
					});
				}
			},
			async getphone(type) {
				if (type == 1) {
					let phoneNumber = this.phoneNumber
					if (!phoneNumber) {  
						uni.showToast({
							title: "请输入手机号",
							icon: 'none',
							duration: 5000,
							mask: true,
						});
						return; }
					$("#prePage").append("开始获取TOKEN" + "\r\n\r\n")
					var Token = this.GetToken();
					if (!Token) {
						$("#prePage").append("获取token失败" + "\r\n\r\n")
						return false;
					}
					var AccessToken = Token.Data.TokenInfo.AccessToken;
					var JwtToken = Token.Data.TokenInfo.JwtToken;
					$("#prePage").append("[getAuthToken]获取accessToken和jwtToken请求后端接口返回：" + JSON.stringify(Token) + "\r\n\r\n")
					checkAuthAvailable(AccessToken, JwtToken) //如果是校验手机号
				} else {
					var Token
					$.ajax({
						url: baseUrl + '/phoneapi/v1.0/gettoken',
						method: "get",
						dataType: "json",
						async: false,
						success: function (data) {
							// this.loading = false
							Token=data
					
						},
						error: function (err) {
						}
					})
				   $("#prePage").append("开始获取TOKEN" + "\r\n\r\n")
				
					$("#prePage").append("[getAuthToken]获取accessToken和jwtToken请求后端接口返回：" + JSON.stringify(Token) + "\r\n\r\n")
					var AccessToken = Token.Data.TokenInfo.AccessToken;
					var JwtToken = Token.Data.TokenInfo.JwtToken;
					$("#prePage").append("[getAuthToken]获取accessToken和jwtToken请求后端接口返回：" + JSON.stringify(Token) + "\r\n\r\n")
					this.checkLoginAvailable(AccessToken, JwtToken) //如果是登录
				}
			},
			//本机号码检验
			checkAuthAvailable(accessToken, jwtToken) {
				this.phoneNumberServer.checkAuthAvailable({
					jwtToken: jwtToken,
					accessToken: accessToken,
					success: function (res) {
						$("#prePage").append("身份鉴权成功" + "\r\n\r\n")
						if (res.code == 600000) {
							this.phoneNumberServer.getVerifyToken({
								success: function (res2) {
								   $("#prePage").append("开始获取spToken " + "\r\n\r\n")
									if (res2.code == 600000) {
										let spToken = res2.spToken
										$("#prePage").append("spToken获取成功：" + spToken + "\r\n\r\n")
										var params = {}
										params.phoneNum = encryptDes(this.phoneNumber,'desenc1!');
										params.SpToken = spToken;
										$("#prePage").append(JSON.stringify(params) + "\r\n\r\n")
										$.ajax({
											headers: {
												"Content-Type": "application/json;charset=utf-8"
											},
											url: this.OneKeyRepairConfig.ApiUrl + this.OneKeyRepairConfig.ApiVerson.v1 + "/home/PhoneReg",
											async: false,
											type: "post",
											data: JSON.stringify(params),
											dataType: "json",
											contentType: "application/json",
											success: function (res3) {
												if (res3.Data.Body.GateVerify.VerifyResult == "PASS") {
													$("#prePage").append("根据SpToken和手机号码返回校验成功，结果返回：" + JSON.stringify(res3) + "\r\n\r\n")
													$("#prePage").append("根据SpToken和手机号码结果返回：" + res3.Data.Body.GateVerify.VerifyResult + "\r\n\r\n")
												}
												else {
													$("#prePage").append('根据SpToken和手机号码返回校验失败，结果返回：' + JSON.stringify(res3) + "\r\n\r\n")
													$("#prePage").append("根据SpToken和手机号码结果返回：" + res3.Data.Body.GateVerify.VerifyResult + "\r\n\r\n")
												}
											},
											error: function (err) {
												$("#prePage").append('根据SpToken和手机号码返回校验异常，结果返回：' + JSON.stringify(err) + "\r\n\r\n")
											}
										});
									} else {
										$("#prePage").append('res2 getVerifyToken:' + JSON.stringify(res2) + "\r\n\r\n")
									}
								},
								error: function (err) {
									$("#prePage").append('err2 getVerifyToken:' + JSON.stringify(err) + "\r\n\r\n")
								}
							})
						}
					},
					error: function (err) {
						$("#prePage").append('err1 getVerifyToken:' + JSON.stringify(err) + "\r\n\r\n")
					}
				});
			},
			//授权登录
			checkLoginAvailable(accessToken, jwtToken) {
				let that=this
				//鉴权接口
				let spToken = ""
				that.phoneNumberServer.checkLoginAvailable({
					accessToken: accessToken,
					jwtToken: jwtToken,
					success: function (res) {
						$("#prePage").append("鉴权结果：" + JSON.stringify(res) + "\r\n\r\n")
						if (res.code === 600000) {
							that.phoneNumberServer.getLoginToken({
								authPageOption: {
									mount: '',  //挂载DIV 默认body
									navBackImg: '',
									subtitle: '', // 副标题
									isHideLogo: false, // logo显示隐藏
									logoImg: baseUrl+'/H5Web/static/login/login1.png', //LOGO图片
									btnText: '立即登录',
									privacyBefore: "我已阅读并同意",
									privacyEnd: "",
									vendorPrivacyPrefix: "《",
									vendorPrivacySuffix: "》",
									privacyVenderIndex: 2,
									isDialog: true, // 是否是弹窗样式
									manualClose: true, // 是否手动关闭弹窗/授权页
									isPrePageType: false, //协议是否前置
									isShowProtocolDesc: false,
									prePageTypeOption: {
									}
								},
								success: res => {
									$("#prePage").append("获取spToken结果成功：" + JSON.stringify(res) + "\r\n\r\n")
									$("#prePage").append("res.code：" + res.code + "\r\n\r\n")
									var aaaa = res.code;
									$("#prePage").append("res.code：" + aaaa + "\r\n\r\n")
									if (aaaa == "600000") {
										// that.phoneNumberServer.closeLoginPage(); // 手动关闭授权页时调用关闭页面
										res.clearInput(); // 清空输入框并将光标置于第一个输入框
										res.focusOn(2); // 将光标置于第1-4个输入框
										// 拿到spToken去服务端发起token验证
										if (res.spToken) {
											$("#prePage").append('根据SpToken查询手机号返回校验异常1111111，结果返回：' + JSON.stringify(res.spToken) + "\r\n\r\n")
											    spToken = res.spToken
												var params = {}
												params.spToken = spToken;
												params.phoneNum = "";
												$.ajax({
													headers: {
														"Content-Type": "application/json;charset=utf-8"
													},
													url:baseUrl+"/phoneapi/v1.0/getPhoneWithToken",
													async: false,
													type: "post",
													data: JSON.stringify(params),
													dataType: "json",
													contentType: "application/json",
													success: function (r2) {
														$("#prePage").append('根据r2结果返回：' + r2 + "\r\n\r\n")
														if(r2.Code==200){															
															// $("#prePage").append('根据SpToken查询手机号成功，结果返回：' + JSON.stringify(r2) + "\r\n\r\n")
															that.phoneNumber=r2.Data.Body.Data.Mobile
															let PhoneNum=encryptDes(that.phoneNumber,'desenc1!').replace('+', '%2B')
															let paramss=`?Phone=${PhoneNum}&type=2`
															$("#prePage").append('paramss，结果返回：' + paramss + "\r\n\r\n")
															that.gettokenbyphone(paramss)																											
														}else{															
															uni.showToast({
																title: r2.Message,
																icon: 'none',
																duration: 5000,
																mask: true,
															});
														}
													},
													error: function (err) {
														$("#prePage").append('根据SpToken查询手机号返回校验异常，结果返回：' + JSON.stringify(err) + "\r\n\r\n")
													}
												});
											
										}else{
											$("#prePage").append('根据SpToken查询手机号返回校验异常222222，结果返回：' + JSON.stringify(res) + "\r\n\r\n")
										}
									} else {
									}
								}, error: res => {
									$("#prePage").append("获取TOKEN结果失败：" + JSON.stringify(res) + "\r\n\r\n")
										uni.showToast({
											title: res.msg,
											icon: 'none',
											duration: 5000,
											mask: true,
										});
									// 提示用户关闭wifi或者尝试其他登录方案
								}, watch: function (status, data) {
									$("#prePage").append("获取watch结果失败：" + JSON.stringify(status) + "\r\n\r\n")
									// 当status为2时整个流程结束，比如如果按钮有loading状态此处置为false
									//1：授权页拉起。
									//2：点击返回按钮。
									//3：点击协议。
									//5：点击登录按钮。
									//6：获取掩码成功。获取此状态时，需了解当前使用的是哪个运营商网络，在预授权模式中，协议和登录按钮需此时展示。
									if (status == 5) {
										$("#prePage").append("spToken：" + status + "\r\n\r\n")                                   
									}
								},
							});
						}
					},
					error: function (res) {
						$("#prePage").append("err:checkLoginAvailable：" + JSON.stringify(res)+ "\r\n\r\n")  
					}
				});
			},
			async gettokenbyphone(params){
				$("#prePage").append('调用返回方法成功：' + 111111111111111 + "\r\n\r\n")
				uni.removeStorageSync('token'); //清除本地token
				uni.removeStorageSync('userName'); //清除本地token
				uni.removeStorageSync('phoneNumber'); //清除本地token
				let that=this
				let data = await  that.$api.gettokenbyphone(params); //已经封装好的api
				$("#prePage").append('根据SpToken查询data成功，结果返回：' + JSON.stringify(data) + "\r\n\r\n")
				if (data.Code == 200) {
					that.disabled = true;
					that.phoneNumberServer.closeLoginPage(); 					
					uni.setStorageSync('token', data.Data.access_token); //保存本地token
					uni.setStorageSync('userName',data.Data.realname);
					uni.setStorageSync('phoneNumber', data.Data.phone); //保存本地token
				} else {
					uni.showToast({
						title: data.Message,
						icon: 'none',
						duration: 5000,
						mask: true,
					});
				}
			}
	    },
	};
</script>

<style lang="less">
	.pageContainer{
		width: 100%;
		height: 100%;
		background: red;
	}
	.main {
		width: 100%;
		height: 100vh;
	}
	.login-form{
	    width: 80%;
	    height: 230px;
	    background: #ffffff;
	    box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.16);
	    border-radius: 15px;
	    margin-top: -150px;
	    margin-left: 27px;
	    display: flex;
	    flex-direction: column;
	    align-items: center;
	    padding-top: 94px;
	    box-sizing: border-box;
	    position: relative;
		margin: -130px auto;
	}
	.login-form-btn{
		width: 80%;
	}
	.policy{
	    display: flex;
	    width: 100%;
	    font-size: 10px;
	    color: #666;
	}

	.main {
	     background: url(@/static/login/bg2.png);
		 background-size: 100%;
		 overflow: hidden;
	}
	.btn-box{
		    margin: 26% auto;
		    width: 80%;
		    // background: white;
		    border-radius: 20px;
		    padding: 20px;
	}
	/deep/.uni-textarea-wrapper{
		height: auto!important;
	}
	/deep/#prePage {
		overflow: auto;
	}
	/deep/.page-type-container .nav .nav-title {
	   color:#ffffff!important;
	}
	/deep/.page-type-container .nav .navText {
	   color:#ffffff!important;
	}
	/deep/.navText {
	   color:#ffffff!important;
	}
	/deep/.dialog-type-container .nav .nav-title {
	   color:#ffffff!important;
	}
	/deep/.nav-title {
	   color:#ffffff!important;
	}
	/deep/.u-image {
	    box-sizing: border-box;
	    margin: 0 auto!important;
	    overflow: hidden;
		height: 246px!important;
	    padding-top: 130px!important;
	}
	uni-button{
		// width:570px!important;
		// height:110px!important;
		background:#3a84f4!important;
		box-shadow:0px 5px 20px #3d86f6!important;
		border-radius:55px!important;
		opacity:1!important;
	}
	/deep/.u-image__image{
	    height: 180px!important;
	}
</style>